package com.lagou.edu.wwyan.web1.minicat;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 自定义类加载器，用来加载webapps下的类
 */
public class LagouClassLoader extends ClassLoader {
    private String basePath;

    public LagouClassLoader(String basePath) {
        this.basePath = basePath;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
//        String myPath = "file:///" + basePath + File.separator + name.replace(".",File.separator) + ".class";
//        String myPath =  path + File.separator + name.replace(".",File.separator) + ".class";
//        myPath = myPath.replaceAll("\\\\","/");
//        System.out.println(myPath);
        byte[] cLassBytes = null;
        Path path = null;
        try {
//            path = Paths.get(new URI(myPath));
            path = new File( basePath + File.separator + name.replace(".",File.separator) + ".class").toPath();
            System.out.println(path.toString());
            cLassBytes = Files.readAllBytes(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Class clazz = defineClass(name, cLassBytes, 0, cLassBytes.length);
        return clazz;
    }
}
